#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle("服务器");
    ui->port->setText("8899");//set the port
    ui->sndMsg->setDisabled(true);

    //创建监听的服务器对象
    m_s = new QTcpServer(this);

    connect(m_s,&QTcpServer::newConnection,this,[=](){
        m_tcp = m_s->nextPendingConnection();
        ui->sndMsg->setEnabled(true);
        m_State->setPixmap(QPixmap(":/connected.jpg").scaled(20,20));
        //检测是否可以接受数据
        connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
          QByteArray data = m_tcp->readAll();
          ui->Record->append("客服端：" + data);
        });

        connect(m_tcp,&QTcpSocket::disconnected,this,[=](){
            //m_tcp->close();
            //m_tcp->deleteLater();
            ui->sndMsg->setDisabled(true);
            m_State->setPixmap(QPixmap(":/disconnected.jpg").scaled(20,20));
        });
    });


    //状态栏
    m_State = new QLabel;
    m_State->setPixmap(QPixmap(":/disconnected.jpg").scaled(20,20));
    ui->statusbar->addWidget(new QLabel("连接对象："));
    ui->statusbar->addWidget(m_State);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_StartListen_clicked()
{
    unsigned short port = ui->port->text().toUShort();
    m_s->listen(QHostAddress::Any,port);
    ui->StartListen->setDisabled(true);
}

void MainWindow::on_sndMsg_clicked()
{
    QString msg = ui->msg->toPlainText();
    m_tcp->write(msg.toUtf8());
    ui->Record->append("服务器："+ msg);
}
